<script lang="ts" setup>
import { addCarAPI, getCarDetailAPI, updateCarAPI } from '@/apis/car';
import router from '@/router';
import type { AddCarParams, UpdateCarParams } from '@/types/car';
import { Back } from '@element-plus/icons-vue';
import { ElMessage, type FormInstance, type FormRules } from 'element-plus';
import { onMounted, ref, watch } from 'vue';
import { useRoute } from 'vue-router';
const route = useRoute()
// 1. 添加月卡
// 车辆信息表单
const carInfoForm = ref<Partial<AddCarParams>>({
  personName: '', // 车主姓名
  phoneNumber: '', // 联系方式
  carNumber: '', // 车牌号码
  carBrand: '', // 车辆品牌
})
const carInfoFormTwo = ref<Partial<AddCarParams>>({
  paymentAmount: '', // 支付金额
  paymentMethod: 'WeChat', // 支付方式
  cardStartDate: '', // 有效时间开始
  cardEndDate: ''
})
//车辆信息表单规则校验
const carInfoFormRules = ref<FormRules<AddCarParams>>({
  personName: [
    { required: true, message: '请输入车主姓名', trigger: 'blur' }
  ],
  phoneNumber: [
    { required: true, message: '请输入联系方式', trigger: 'blur' },
    { validator: (rule, value) => /^1[3-9]\d{9}$/.test(value), message: '请输入正确的手机号', trigger: 'blur' }
  ],
  carNumber: [
    { required: true, message: '请输入车牌号码', trigger: 'blur' },
    { validator: (rule, value) => /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1}$/.test(value), message: '请输入正确的车牌号', trigger: 'blur' }
  ],
  carBrand: [
    { required: true, message: '请输入车辆品牌', trigger: 'blur' }
  ],
})
const carInfoFormTwoRules = ref<FormRules<AddCarParams>>({
  paymentAmount: [
    { required: true, message: '请输入支付金额', trigger: 'blur' }
  ],
  paymentMethod: [
    { required: true, message: '请选择支付方式', trigger: 'blur' }
  ],
  cardEndDate: [
    { required: true, message: '请选择有效时间', trigger: 'blur' }
  ]
})
//支付日期
const date = ref<string[]>([]);
//监听支付日期变化
watch(date, () => {
  if (date.value) {
    carInfoFormTwo.value.cardStartDate = date.value[0]
    carInfoFormTwo.value.cardEndDate = date.value[1]
  } else {
    carInfoFormTwo.value.cardStartDate = ''
    carInfoFormTwo.value.cardEndDate = ''
  }
})
//编辑页面rechargeId和carInfoId
const rechargeId_ = ref(0)
const carInfoId_ = ref(0)
//表单
const carInfoFormRef = ref<FormInstance>()
const carInfoFormTwoRef = ref<FormInstance>()
//重置表单
const resetForms = () => {
  carInfoFormRef.value?.resetFields()
  carInfoFormTwoRef.value?.resetFields()
  date.value = []
}
//提交表单
const submit = async () => {
  try{
    await addCarAPI({ ...carInfoForm.value, ...carInfoFormTwo.value } as AddCarParams)
    router.back()
    ElMessage.success('添加成功！')
  }catch(err:any){
    ElMessage.error(err.response.data.msg)
  }
}
//判断是否为编辑页面并渲染编辑页面
onMounted(async () => {
  if (route.params.id) {
    //渲染编辑页面
    const res = await getCarDetailAPI(route.params.id as string)
    console.log(res);
    const { personName, phoneNumber, carNumber, carBrand, paymentAmount, paymentMethod, cardStartDate, cardEndDate, rechargeId, carInfoId } = res.data
    carInfoForm.value = {
      personName, // 车主姓名
      phoneNumber, //联系方式
      carNumber, // 车牌号码
      carBrand, // 车辆品牌
    }
    carInfoFormTwo.value = {
      paymentAmount,// 支付金额
      paymentMethod, // 支付方式
      cardStartDate,// 有效时间开始
      cardEndDate
    }
    date.value=[cardStartDate,cardEndDate]
    rechargeId_.value = rechargeId
    carInfoId_.value = carInfoId
  }
})
//修改月卡
const updateCar = async () => {
  try {
    await updateCarAPI({ ...carInfoForm.value, ...carInfoFormTwo.value, rechargeId: rechargeId_.value, carInfoId: carInfoId_.value } as UpdateCarParams)
    router.back()
    ElMessage.success('修改成功！')
  } catch (err: any) {
    ElMessage.error(err.response.data.msg)
  }
}
</script>
<template>
  <el-card>
    <template #header>
      <div class="card-header" style="display: flex;align-items: center;">
        <el-link type="primary" style="color: black;font-size: 16px;" :underline="false"
          @click="router.back()"><el-icon>
            <Back />
          </el-icon>返回</el-link>
        <span style="margin:0 10px;color: #E0E3E8;">|</span>
        <span v-if="route.params.id">编辑月卡</span>
        <span v-else>添加月卡</span>
      </div>
    </template>
    <div style="background-color: #F4F6F8;display: flex;flex-direction: column;padding: 20px 200px;">
      <el-card>
        <template #header>
          <div class="card-header">
            <span>车辆信息</span>
          </div>
        </template>
        <el-form ref="carInfoFormRef" :model="carInfoForm" :rules="carInfoFormRules" label-width="100px">
          <el-form-item label="车主姓名" prop="personName">
            <el-input v-model="carInfoForm.personName" />
          </el-form-item>
          <el-form-item label="联系方式" prop="phoneNumber">
            <el-input v-model="carInfoForm.phoneNumber" maxlength="11" />
          </el-form-item>
          <el-form-item label="车辆号码" prop="carNumber">
            <el-input v-model="carInfoForm.carNumber" />
          </el-form-item>
          <el-form-item label="车辆品牌" prop="carBrand">
            <el-input v-model="carInfoForm.carBrand" />
          </el-form-item>
        </el-form>
      </el-card>
      <el-card style="margin-top: 20px;">
        <template #header>
          <div class="card-header">
            <span>最近一次月卡缴费信息</span>
          </div>
        </template>
        <el-form :model="carInfoFormTwo" :rules="carInfoFormTwoRules" label-width="100px" ref="carInfoFormTwoRef">
          <el-form-item label="有效日期" prop="cardEndDate">
            <el-date-picker v-model="date" type="daterange" range-separator="To" start-placeholder="Start date"
              end-placeholder="End date" />
          </el-form-item>
          <el-form-item label="支付金额" prop="paymentAmount">
            <el-input v-model="carInfoFormTwo.paymentAmount" />
          </el-form-item>
          <el-form-item label="支付方式" prop="paymentMethod">
            <el-select v-model="carInfoFormTwo.paymentMethod">
              <el-option v-for="item in ['Alipay', 'WeChat', 'Cash']" :key="item" :value="item"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
    <template #footer>
      <div style="width: 100%;display: flex;justify-content: center;">
        <el-button @click="resetForms">重置</el-button>
        <el-button type="primary" @click="submit" v-if="!route.params.id">确定</el-button>
        <el-button type="primary" @click="updateCar" v-else>修改</el-button>
      </div>
    </template>
  </el-card>
</template>
<style></style>